package com.fw.ui.view.settings.usercontrol.merchantuser.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.service.bean.EntryBean;
import com.fw.service.bean.ErrorBean;
import com.fw.service.merchantuser.bean.MerchantUserBean;
import com.fw.ui.ApplicationUI;
import com.fw.ui.bao.MasterDataBAO;
import com.fw.ui.bao.MerchantUserBAO;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.bao.PropertyBAO;
import com.fw.ui.util.SessionInfoUtils;
import com.fw.ui.util.UICommonUtils;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.common.ConfirmDialogWindow;
import com.fw.ui.view.event.AbstractButtonClickListener;
import com.fw.ui.view.settings.usercontrol.merchantuser.EditMerchantUserView;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class EditMerchantUserSaveButtonClickListener extends AbstractButtonClickListener {

    private static final long serialVersionUID = 1L;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private MerchantUserBAO merchantuserBAO;
    @Autowired
    private MessageBAO messageBAO;
    @Autowired
    private PropertyBAO propertyBAO;
    @Autowired
    private MasterDataBAO masterDataBAO;
    @Autowired
    private UICommonUtils uiCommonUtils;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> click(ClickEvent event) throws Exception {
	EditMerchantUserView editMerchantUserView = (EditMerchantUserView) this.getBasedComponent();

	String email = editMerchantUserView.getTxtEmail().getValue();
	String name = editMerchantUserView.getTxtName().getValue();
	String role = (String) editMerchantUserView.getCbbGroup().getValue();
	String status = (String) editMerchantUserView.getCbbStatus().getValue();

	MerchantUserBean oldMerchantUserBean = editMerchantUserView.getMerchantUserBean();

	MerchantUserBean merchantUserBean = new MerchantUserBean();
	BeanUtils.copyProperties(oldMerchantUserBean, merchantUserBean);
	merchantUserBean.setEmail(email);
	merchantUserBean.setName(name);
	merchantUserBean.setRole(role);
	merchantUserBean.setStatus(status);

	ApplicationUI applicationUI = (ApplicationUI) editMerchantUserView.getUI();
	sessionInfoUtils.setSessionInfoDetails(merchantUserBean, applicationUI.getAuthenticationBean(), applicationUI.getLocale());

	Map<String, Serializable> mapResult = this.merchantuserBAO.updateMerchantUser(merchantUserBean);
	Map<String, Object> result = new HashMap<String, Object>();
	if (mapResult != null) {
	    List<ErrorBean> errorBeans = (List<ErrorBean>) mapResult.get(List.class.getName() + "." + ErrorBean.class.getName());
	    MerchantUserBean resultMerchantUserBean = (MerchantUserBean) mapResult.get(MerchantUserBean.class.getName());
	    if (errorBeans != null && !errorBeans.isEmpty()) {
		result.put(MessageBAO.MESSAGE_WARNING_TYPE, errorBeans);
	    } else {
		if (resultMerchantUserBean != null && resultMerchantUserBean.getId() != null) {
		    editMerchantUserView.setMerchantUserBean(resultMerchantUserBean);

		    if (merchantUserBean.getMerchantID() != null) {
			uiCommonUtils.setValueUIComponent(editMerchantUserView.getOgMerchantOrParentId(),
				editMerchantUserView.getMerchantOption());
			List<EntryBean<Long, String>> merchantProfiles = masterDataBAO.selectAllMerchantUserMerchantProfile();
			if (merchantProfiles != null) {
			    for (EntryBean<Long, String> entry : merchantProfiles) {
				editMerchantUserView.getCbbMerchant().addItem(entry.getValue());
				editMerchantUserView.getCbbMerchant().setItemCaption(entry.getValue(), entry.getValue());
			    }
			}
			uiCommonUtils.setValueUIComponent(editMerchantUserView.getCbbMerchant(), merchantUserBean.getMerchantID());
		    }
		    if (merchantUserBean.getParentID() != null) {
			uiCommonUtils.setValueUIComponent(editMerchantUserView.getOgMerchantOrParentId(),
				editMerchantUserView.getParentOption());
			List<EntryBean<Long, String>> parentMerchants = masterDataBAO.selectAllMerchantUserParentMerchant();
			if (parentMerchants != null) {
			    for (EntryBean<Long, String> entry : parentMerchants) {
				editMerchantUserView.getCbbParent().addItem(entry.getValue());
				editMerchantUserView.getCbbParent().setItemCaption(entry.getValue(), entry.getValue());
			    }
			}
			uiCommonUtils.setValueUIComponent(editMerchantUserView.getCbbParent(), merchantUserBean.getParentID());
		    }
		    uiCommonUtils.setValueUIComponent(editMerchantUserView.getTxtUsername(), resultMerchantUserBean.getUsername());
		    uiCommonUtils.setValueUIComponent(editMerchantUserView.getTxtName(), resultMerchantUserBean.getName());
		    uiCommonUtils.setValueUIComponent(editMerchantUserView.getTxtEmail(), resultMerchantUserBean.getEmail());
		    uiCommonUtils.setValueUIComponent(editMerchantUserView.getCbbGroup(), resultMerchantUserBean.getRole());
		    uiCommonUtils.setValueUIComponent(editMerchantUserView.getCbbStatus(), resultMerchantUserBean.getStatus());

		    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(editMerchantUserView);

		    List<EntryBean<String, String>> statuses = masterDataBAO.selectMerchantUserStatusByCurrentStatus(resultMerchantUserBean
			    .getStatus());
		    if (statuses != null && !statuses.isEmpty()) {
			editMerchantUserView.getCbbStatus().removeAllItems();
			for (EntryBean<String, String> entry : statuses) {
			    editMerchantUserView.getCbbStatus().addItem(entry.getKey());
			    editMerchantUserView.getCbbStatus().setItemCaption(entry.getKey(), entry.getValue());
			}
			editMerchantUserView.getCbbStatus().setValue(resultMerchantUserBean.getStatus());
			editMerchantUserView.getCbbStatus().select(resultMerchantUserBean.getStatus());
		    }

		    String activeStatus = propertyBAO
			    .getPropertyValue("com.fw.ui.view.settings.usercontrol.merchantuser.EditMerchantUserView.exclude.status.item.active");
		    if (!activeStatus.equals(resultMerchantUserBean.getStatus())) {
			uiCommonUtils.setEnableUIComponent(editMerchantUserView.getBtnResetPassword(), false);
		    } else {
			uiCommonUtils.setEnableUIComponent(editMerchantUserView.getBtnResetPassword(), true);
		    }

		    String closeStatus = propertyBAO
			    .getPropertyValue("com.fw.ui.view.settings.usercontrol.merchantuser.EditMerchantUserView.exclude.status.item.closed");
		    if (closeStatus.equals(resultMerchantUserBean.getStatus())) {
			this.setAutoEnabled(false);
			List<com.vaadin.ui.Component> componentsEnable = new ArrayList<com.vaadin.ui.Component>();
			componentsEnable.add(editMerchantUserView.getBtnCancel());
			uiCommonUtils.setEnableAllUIComponent(editMerchantUserView, componentsEnable, false);
		    }

		    if (activeStatus.equals(resultMerchantUserBean.getStatus()) && !activeStatus.equals(oldMerchantUserBean.getStatus())) {
			String title = messageBAO.getMessage("message.dialog.title.info");
			String[] params = new String[] { resultMerchantUserBean.getPassword() };
			String content = messageBAO.getMessageWithParams(
				"com.fw.ui.view.settings.usercontrol.merchantuser.EditMerchantUserView.message.updated.resetpassword",
				params);
			String okCaption = messageBAO.getMessage("application.button.ok.caption");

			ConfirmDialogWindow.createConfirmDialog(editMerchantUserView.getUI(), title, content, okCaption, null, "150px",
				"500px");
			return null;
		    }

		    result.put(MessageBAO.MESSAGE_INFO_TYPE,
			    "com.fw.ui.view.settings.usercontrol.merchantuser.EditMerchantUserView.message.updated");
		} else {
		    result.put(MessageBAO.MESSAGE_WARNING_TYPE,
			    "com.fw.ui.view.settings.usercontrol.merchantuser.EditMerchantUserView.message.failed");
		}
	    }
	} else {
	    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "message.error.common");
	}

	return result;
    }

    @Override
    public boolean validate(ClickEvent event) {
	EditMerchantUserView editMerchantUserView = (EditMerchantUserView) this.getBasedComponent();
	try {

	    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(editMerchantUserView);

	    boolean emailValid = editMerchantUserView.getTxtEmail().isValid();
	    boolean nameValid = editMerchantUserView.getTxtName().isValid();
	    boolean groupValid = editMerchantUserView.getCbbGroup().isValid();
	    boolean statusValid = editMerchantUserView.getCbbStatus().isValid();

	    if (emailValid && nameValid && groupValid && groupValid) {
		return true;
	    } else {
		if (!emailValid) {
		    editMerchantUserView.getTxtEmail().addStyleName("v-textfield-error");
		    if (editMerchantUserView.getTxtEmail().getErrorMessage() != null) {
			editMerchantUserView.getLblEmailValidateMessage().setValue(
				editMerchantUserView.getTxtEmail().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editMerchantUserView.getRow3Validate().setVisible(true);
		}
		if (!nameValid) {
		    editMerchantUserView.getTxtName().addStyleName("v-textfield-error");
		    if (editMerchantUserView.getTxtName().getErrorMessage() != null) {
			editMerchantUserView.getLblNameValidateMessage().setValue(
				editMerchantUserView.getTxtName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editMerchantUserView.getRow4Validate().setVisible(true);
		}
		if (!groupValid) {
		    editMerchantUserView.getCbbGroup().addStyleName("v-filterselect-error");
		    if (editMerchantUserView.getCbbGroup().getErrorMessage() != null) {
			editMerchantUserView.getLblGroupValidateMessage().setValue(
				editMerchantUserView.getCbbGroup().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editMerchantUserView.getRow5Validate().setVisible(true);
		}
		if (!statusValid) {
		    editMerchantUserView.getCbbStatus().addStyleName("v-filterselect-error");
		    if (editMerchantUserView.getCbbStatus().getErrorMessage() != null) {
			editMerchantUserView.getLblGroupValidateMessage().setValue(
				editMerchantUserView.getCbbStatus().getErrorMessage().getFormattedHtmlMessage());
		    }
		    editMerchantUserView.getRow5Validate().setVisible(true);
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return false;
	}
	return false;
    }

}
